package com.caoustc.okhttplib.okhttp

import android.text.TextUtils
import okhttp3.Call
import java.util.concurrent.ConcurrentHashMap

internal class OkHttpCallManager private constructor() {
    private val callMap: ConcurrentHashMap<String?, Call>
    private val callTagMap //标识某一请求的当前tag值
            : ConcurrentHashMap<String?, Int>?

    fun addCall(url: String?, call: Call?) {
        if (call != null && !TextUtils.isEmpty(url)) {
            callMap[url] = call
        }
    }

    fun getCall(url: String?): Call? {
        return if (!TextUtils.isEmpty(url)) {
            callMap[url]
        } else null
    }

    fun removeCall(url: String?) {
        if (!TextUtils.isEmpty(url)) {
            callMap.remove(url)
        }
    }

    fun clearCall() {
        for ((key, call) in callMap) {
            if (call != null) {
                call.cancel()
            }
            callMap.remove(key)
        }
    }

    fun addCallTag(url: String?, tag: Int) {
        if (!TextUtils.isEmpty(url)) {
            callTagMap!![url] = tag
        }
    }

    fun getCallTag(url: String?): Int? {
        return if (!TextUtils.isEmpty(url)) {
            callTagMap!![url]
        } else null
    }

    fun removeCallTag(url: String?) {
        if (!TextUtils.isEmpty(url) && callTagMap != null && callTagMap.containsKey(url)) {
            callTagMap.remove(url)
        }
    }

    fun clearCallTag() {
        callTagMap!!.clear()
    }

    companion object {
        @Volatile
        private var mOkHttpCallManager: OkHttpCallManager? = null
        val instance: OkHttpCallManager?
            get() {
                synchronized(OkHttpCallManager::class.java) {
                    if (mOkHttpCallManager == null) {
                        mOkHttpCallManager = OkHttpCallManager()
                    }
                }
                return mOkHttpCallManager
            }
    }

    init {
        callMap = ConcurrentHashMap()
        callTagMap = ConcurrentHashMap()
    }
}